package org.support.small.mallms.controller;

import com.mybatisflex.core.constant.SqlOperator;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.query.SqlOperators;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.support.small.infrastructure.utils.WebUtils;
import org.support.small.infrastructure.website.Banners;
import org.support.small.infrastructure.Tables;
import org.support.small.mallms.contants.URLContants;
import org.support.small.mallms.contants.WebSiteURLContants;
import org.support.small.mallms.model.Ret;
import org.support.small.mallms.query.BannersQuery;
import org.support.small.mallms.service.BannersService;
import org.support.small.mallms.utils.RequestContextUtils;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping(WebSiteURLContants.PREFIX_BANNERS)
public class BannersController {
    @Resource
    private BannersService bannersService;

    @PostMapping(URLContants.SEARCH)
    public Ret<Page<Banners>> search(@RequestBody BannersQuery query, Page<Banners> page) {
        Long adminId = RequestContextUtils.getAdminId();
        SqlOperators sqlOperators = SqlOperators.of()
                .set(BannersQuery::getTitle, SqlOperator.LIKE);

        QueryWrapper queryWrapper = WebUtils.createQuery(query, sqlOperators,
                Tables.BANNERS.UPDATE_TIME.desc());
        bannersService.search(page, queryWrapper);
        return Ret.ok(page);
    }

    @GetMapping(URLContants.ID)
    public Ret<Banners> detail(@PathVariable Long id) {
        Banners banners = bannersService.get(id);
        return Ret.ok(banners);
    }

    @GetMapping(URLContants.DELETE)
    public Ret<Void> delete(Long id) {
        bannersService.delete(id);
        return Ret.ok();
    }

    @PostMapping(URLContants.SAVE)
    public Ret<Void> save(@RequestBody @Validated Banners banners) {
        bannersService.save(banners);
        return Ret.ok();
    }
}
